package com.groupbuying.store.service.impl.agent;

import com.google.common.base.Strings;
import com.groupbuying.store.connector.SysconfigFeign;
import com.groupbuying.store.constants.CommonConstants;
import com.groupbuying.store.constants.StoreAccountEnumConstants;
import com.groupbuying.store.constants.StoreConstants;
import com.groupbuying.store.controller.agent.StoreAgentAccountController;
import com.groupbuying.store.dao.StoreMainInfoDao;
import com.groupbuying.store.dao.agent.StoreAgentAccountDao;
import com.groupbuying.store.dao.forManage.StoreAccountRoleDao;
import com.groupbuying.store.dao.forManage.StoreRoleDao;
import com.groupbuying.store.dao.forManage.StoreRoleMenuDao;
import com.groupbuying.store.domain.StoreMainInfoDO;
import com.groupbuying.store.domain.agent.StoreAgentAccountDO;
import com.groupbuying.store.domain.forManage.StoreAccountRoleDO;
import com.groupbuying.store.domain.forManage.StoreRoleDO;
import com.groupbuying.store.domain.forManage.StoreRoleMenuDO;
import com.groupbuying.store.dto.forManage.StoreOperDTO;
import com.groupbuying.store.dto.forManage.StoreShopManagePageDTO;
import com.groupbuying.store.pojo.StoreAccountEnum;
import com.groupbuying.store.service.StoreAccountService;
import com.groupbuying.store.service.agent.StoreAgentAccountService;
import com.groupbuying.store.utils.*;
import com.groupbuying.store.utils.apiresult.ApiResult;
import com.groupbuying.store.utils.apiresult.ApiResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class StoreAgentAccountServiceImpl implements StoreAgentAccountService {
	public static final Logger logger = LoggerFactory.getLogger(StoreAgentAccountController.class);

	@Autowired
	private StoreAgentAccountDao storeAccountDao;
	@Autowired
	private SysconfigFeign sysconfigFeign;
	@Autowired
	private StoreAccountService storeAccountService;
	@Autowired
	StoreRoleDao storeRoleDao;
	@Autowired
	StoreRoleMenuDao storeRoleMenuDao;
	@Autowired
	StoreAccountRoleDao storeAccountRoleDao;
	@Autowired
	private StoreMainInfoDao storeMainInfoDao;
	@Override
	public StoreAgentAccountDO get(String accountId){
		return storeAccountDao.get(accountId);
	}
	
	@Override
	public List<StoreAgentAccountDO> list(Map<String, Object> map){
		return storeAccountDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return storeAccountDao.count(map);
	}
	
	@Override
	public int save(StoreAgentAccountDO storeAccount){
		/*获取服务商id*/
		String accountId = sysconfigFeign.getStoreAcountByLeaf();
		storeAccount.setAccountId(accountId);
		String providerId = sysconfigFeign.getStoreProviderByLeaf();
		storeAccount.setProviderId(providerId);
		String createdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		storeAccount.setOperTime(createdate);
		storeAccount.setDelFlag(StoreAccountEnumConstants.ENUM_DELFLAG_UNDEL);
		storeAccount.setCreateOpeTime(createdate);
		storeAccount.setStatus(StoreAccountEnumConstants.ENUM_STATUS_NORMAL);
		storeAccount.setProviderType(StoreAccountEnumConstants.ENUM_PROVIDERTYPE_MAIN);
		storeAccount.setPassword(MD5Utils.encrypt(storeAccount.getAccountName(), storeAccount.getPassword()));
		StoreAgentAccountDO storeAccountDO_exit = this.getByAccountName(storeAccount.getAccountName());
		if (storeAccountDO_exit != null) {
			logger.info("StoreAgentAccountServiceImpl.save()----->登录账号已存在,对应的服务商名称为:"+storeAccount.getAccountName());
			return 0;
		}
		return storeAccountDao.save(storeAccount);
	}
	
	@Override
	public int update(StoreAgentAccountDO storeAccount){
		return storeAccountDao.update(storeAccount);
	}
	
	@Override
	public int remove(String accountId){
		return storeAccountDao.remove(accountId);
	}
	
	@Override
	public int batchRemove(String[] accountIds){
		return storeAccountDao.batchRemove(accountIds);
	}

	@Override
	public StoreAgentAccountDO getByAccountName(String accountName) {
		Map map_repeat = new HashMap();
		map_repeat.put("accountName", accountName);
		List<StoreAgentAccountDO> list_repeat = this.storeAccountDao.list(map_repeat);
		if (list_repeat.size() > 0) {
			return list_repeat.get(0);
		}
		return null;
	}
	/**
	 * 通过代理商添加服务商
	 */
	@Override
	public ApiResult saveAccount(Map<String,Object> condMap) {

		try {
			StoreAgentAccountDO storeAgentAccountDO = (StoreAgentAccountDO) BeanOrMapConvertUtils.mapToObjects(condMap, StoreAgentAccountDO.class);
			if (Strings.isNullOrEmpty(storeAgentAccountDO.getAccountName()) || Strings.isNullOrEmpty(storeAgentAccountDO.getPassword()) || Strings.isNullOrEmpty(storeAgentAccountDO.getName()) || Strings.isNullOrEmpty(storeAgentAccountDO.getProviderName()) || Strings.isNullOrEmpty(storeAgentAccountDO.getMobile())) {
				return ApiResult.paramIsNull();
			}
			/*获取代理商id*/
			String agentId = (String) condMap.get("agentId");
			String accountName = storeAgentAccountDO.getAccountName();
			logger.info("StoreAgentAccountServiceImpl.saveAccount()----->获取到的代理商为id:"+agentId);
			// 创建账号
			storeAgentAccountDO.setAgentId(agentId);
			String uuid = sysconfigFeign.getStoreAcountByLeaf();
			String pro = sysconfigFeign.getStoreProviderByLeaf();
			storeAgentAccountDO.setAccountId(uuid);
			storeAgentAccountDO.setAccountNo(sysconfigFeign.getUuidByLeaf());
			storeAgentAccountDO.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);
			storeAgentAccountDO.setStatus(CommonConstants.COMMON_STATE_UES);
			storeAgentAccountDO.setProviderId(pro);
			storeAgentAccountDO.setProviderType(StoreConstants.STORE_MAIN_ACCOUNT);
			storeAgentAccountDO.setFreezestatus(CommonConstants.COMMON_FREEZESTATUS);
			//添加服务商初始状态--2待审核状态
			storeAgentAccountDO.setStatus(StoreAccountEnumConstants.ENUM_STATUS_WAIT);
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String createdate = sdf.format(date);
			storeAgentAccountDO.setCreateOpeTime(createdate);
			storeAgentAccountDO.setPassword(MD5Utils.encrypt(storeAgentAccountDO.getAccountName(),storeAgentAccountDO.getPassword()));
			StoreAgentAccountDO storeAccountDO_exit = this.getByAccountName(storeAgentAccountDO.getAccountName());
			if (storeAccountDO_exit != null) {
                logger.info("StoreAgentAccountServiceImpl.saveAccount()----->"+accountName+"登录账号已存在");
				return ApiResult.failure(ApiResultCode.LOGINNAMEEXISTS.code(),ApiResultCode.LOGINNAMEEXISTS.message());
			}
			StoreAgentAccountDO storeAccountDO_pro = this.getByProviderNameAndAgentId(storeAgentAccountDO.getProviderName(),agentId);
			if (storeAccountDO_pro != null) {
                logger.info("StoreAgentAccountServiceImpl.saveAccount()----->"+accountName+"服务商名称已存在");
				return ApiResult.failure(ApiResultCode.PROVIDEREXISTS.code(),ApiResultCode.PROVIDEREXISTS.message());
			}
			/*通过代理商保存服务商数据*/
			int accountStates = storeAccountDao.save(storeAgentAccountDO);
			// 建立角色
			StoreRoleDO storeRoleDO = new StoreRoleDO();
			storeRoleDO.setRoleName(StoreAccountEnum.STORE_ADMIN_TITLE);
			storeRoleDO.setRoleSign(StoreAccountEnum.STORE_ADMIN_REMARK);
			storeRoleDO.setProviderId(storeAgentAccountDO.getProviderId());
			int roleStates = storeRoleDao.save(storeRoleDO);
			// 角色关联权限，管理最高权限
			List<StoreRoleMenuDO> list = new ArrayList<>();
			Map roleBest = new HashMap();
			roleBest.put("roleId", StoreAccountEnum.STORE_ADMIN_ID);
			List<StoreRoleMenuDO> list_role = storeRoleMenuDao.list(roleBest);
			System.out.println(list_role.size());
			for (StoreRoleMenuDO role : list_role) {
				StoreRoleMenuDO storeRoleMenuDO = new StoreRoleMenuDO();
				storeRoleMenuDO.setRoleId(storeRoleDO.getRoleId());
				storeRoleMenuDO.setMenuId(role.getMenuId());
				list.add(storeRoleMenuDO);
			}
			if (list.size() > 0) {
				storeRoleMenuDao.batchSave(list);
			}
			// 账号关联角色
			StoreAccountRoleDO storeAccountRoleDO = new StoreAccountRoleDO();
			//storeAccountRoleDO.setId(sysconfigFeign.getUuidByLeaf());
			storeAccountRoleDO.setAccountId(storeAgentAccountDO.getAccountId());
			storeAccountRoleDO.setRoleId(storeRoleDO.getRoleId());
			int accountRoleStates = storeAccountRoleDao.save(storeAccountRoleDO);
			if (accountStates > 0 && roleStates > 0 && accountRoleStates > 0) {
                logger.info("StoreAgentAccountServiceImpl.saveAccount()----->"+accountName+"注册成功");
				return ApiResult.success();
			}
            logger.info("StoreAgentAccountServiceImpl.saveAccount()----->"+accountName+"注册失败 accountStates："+accountStates
            +",roleStates:"+roleStates+",accountRoleStates:"+accountRoleStates);
		} catch (Exception e) {
            logger.info("StoreAgentAccountServiceImpl.saveAccount()----->系统出错:",e);
            return ApiResult.failure("系统错误");
		}
		return ApiResult.failure();
	}
	/**
	 * 更新一条数据
	 */
	@Override
	public int updateStatus(Map<String, Object> map) {

		return this.storeAccountDao.updateStatus(map);
	}
	/**
	 *通过代理商查出门店信息
	 */
	@Override
	public PageUtils storeMainInfoListByAgent(Map<String, Object> map) {
		map.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
		map.put("sort", "createOpeTime");
		map.put("order", "desc");
		Query query = new Query(map);
		List<StoreShopManagePageDTO> smi= storeAccountDao.getListByManagePage(query);
		int count = storeAccountDao.getListByManageCount(query);
		PageUtils pageUtil = new PageUtils(smi, count);
		return pageUtil;

	}
	/**
	 * 通过代理商id查询运营人员管理列表
	 */
	@Override
	public PageUtils getStoreOperList(Map<String, Object> map) {
		/*通过代理商id获取服务商列表*/
		map.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
		map.put("sort", "createOpeTime");
		map.put("order", "desc");
		Query query = new Query(map);
		List<StoreOperDTO> smi = storeAccountDao.getStoreOpersList(query);
		map.remove("limit");
		map.remove("page");
		query = new Query(map);
		List<StoreOperDTO> totalList = storeAccountDao.getStoreOpersList(query);
		PageUtils pageUtil = new PageUtils(smi, totalList.size());
		return pageUtil;
	}
	/**
	 * 编辑代理商
	 */
	@Override
	public R setStoreOper(Map<String, Object> params) {
		Object temp = params.get("storeUuid");
		String storeUuid = temp != null ? temp.toString() : "";
		temp = params.get("operateMan");
		String operateMan = temp != null ? temp.toString() : "";
		temp = params.get("operateTel");
		String operateTel = temp != null ? temp.toString() : "";
		temp = params.get("operateNote");
		String operateNote = temp != null ? temp.toString() : "";

		StoreMainInfoDO storeMainInfoDO = storeMainInfoDao.get(storeUuid);
		if(storeMainInfoDO == null){
			return R.error();
		}
		storeMainInfoDO.setOperateman(operateMan);
		storeMainInfoDO.setOperatetel(operateTel);
		storeMainInfoDO.setWeixin(operateNote);

		storeMainInfoDao.update(storeMainInfoDO);
		return R.ok();
	}

	/**
	 * 判断服务商账号是否存在
	 */
	private StoreAgentAccountDO getByProviderNameAndAgentId(String providerName,String agentId) {
		Map map_repeat = new HashMap();
		map_repeat.put("providerName", providerName);
		map_repeat.put("agentId", agentId);
		List<StoreAgentAccountDO> list_repeat = storeAccountDao.list(map_repeat);
		if (list_repeat.size() > 0) {
			return list_repeat.get(0);
		}
		return null;
	}

}
